/*
 * Copyright (c) 2019 the Eclipse Milo Authors
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 */

package com.xj.opcua.server;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.core.AccessLevel;
import org.eclipse.milo.opcua.sdk.core.Reference;
import org.eclipse.milo.opcua.sdk.server.Lifecycle;
import org.eclipse.milo.opcua.sdk.server.OpcUaServer;
import org.eclipse.milo.opcua.sdk.server.api.DataItem;
import org.eclipse.milo.opcua.sdk.server.api.ManagedNamespaceWithLifecycle;
import org.eclipse.milo.opcua.sdk.server.api.MonitoredItem;
import org.eclipse.milo.opcua.sdk.server.model.nodes.objects.BaseEventTypeNode;
import org.eclipse.milo.opcua.sdk.server.model.nodes.objects.ServerTypeNode;
import org.eclipse.milo.opcua.sdk.server.nodes.UaFolderNode;
import org.eclipse.milo.opcua.sdk.server.nodes.UaNode;
import org.eclipse.milo.opcua.sdk.server.nodes.UaVariableNode;
import org.eclipse.milo.opcua.sdk.server.nodes.filters.AttributeFilters;
import org.eclipse.milo.opcua.sdk.server.util.SubscriptionModel;
import org.eclipse.milo.opcua.stack.core.Identifiers;
import org.eclipse.milo.opcua.stack.core.UaException;
import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xj.opcua.client.Client;
import com.xj.opcua.client.ClientRunner;
import com.xj.opcua.client.manager.DataTypeDictionaryManager;
import com.xj.opcua.client.manager.OpcUaClientManager;
import com.xj.opcua.client.util.OpcUaClentUtils;
import com.xj.opcua.filter.AttributeLoggingFilter;

import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.ubyte;
import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.ushort;

public class Namespace extends ManagedNamespaceWithLifecycle {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private volatile Thread eventThread1;
    private volatile boolean keepPostingEvents = true;

    private final DataTypeDictionaryManager dictionaryManager;

    private final SubscriptionModel subscriptionModel;

    public Namespace(OpcUaServer server) {
        super(server, CreateAndAddNodes.NAMESPACE_URI2);

        subscriptionModel = new SubscriptionModel(server, this);
        dictionaryManager = new DataTypeDictionaryManager(getNodeContext(), CreateAndAddNodes.NAMESPACE_URI2);

        getLifecycleManager().addLifecycle(dictionaryManager);
        getLifecycleManager().addLifecycle(subscriptionModel);

        getLifecycleManager().addStartupTask(this::createAndAddDataBlocksGlobalNodes);

        getLifecycleManager().addLifecycle(new Lifecycle() {
            @Override
            public void startup() {
                startBogusEventNotifier();
            }

            @Override
            public void shutdown() {
                try {
                    keepPostingEvents = false;
                    eventThread1.interrupt();
                    eventThread1.join();
                } catch (InterruptedException ignored) {
                    // ignored
                }
            }
        });
    }

    /**
     * 添加DataBlocksGlobal节点信息
     */
    private void createAndAddDataBlocksGlobalNodes() {
    	//for(int i=0;i<Client.urList.size();i++) {
		//	String url = Client.urList.get(i);
		//	String subNodeString = Client.subNodeList.get(i);
		//	createAndAddDataBlocksGlobalNodes(i+1,url,subNodeString);
		//}
    }
    
    private void createAndAddDataBlocksGlobalNodes(int i,String url,String subNodeString) {
    	if("".equalsIgnoreCase(subNodeString)) {
    		return;
		}
    	NodeId folderNodeId = new NodeId(2, subNodeString);
    	OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url);
    	if(opcUaClient==null) {
    		Client client = new OpcUaClientManager(url);
	        try {
				new ClientRunner(client).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
	        opcUaClient = OpcUaClentUtils.getOpcUaClent(url);
    	}
    	try {
			org.eclipse.milo.opcua.sdk.client.nodes.UaNode rootNode = opcUaClient.getAddressSpace().getNode(folderNodeId);
			String name = rootNode.getBrowseName().getName();
        	Object identifier = rootNode.getNodeId().getIdentifier();
			UaFolderNode folderNode = new UaFolderNode(
		            getNodeContext(),
		            newNodeId(identifier.toString()),
		            newQualifiedName(name),
		            LocalizedText.english(name)
		        );

		        getNodeManager().addNode(folderNode);

		        // Make sure our new folder shows up under the server's Objects folder.
		        folderNode.addReference(new Reference(
		            folderNode.getNodeId(),
		            Identifiers.Organizes,
		            Identifiers.ObjectsFolder.expanded(),
		            false
		        ));

		        // Add the rest of the nodes
		        NodeId nodeId = new NodeId(2,subNodeString);
		        addDataBlocksGlobalNodes(folderNode,nodeId,url);
		} catch (UaException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public void addDataBlocksGlobalNodes(UaFolderNode folderNode,NodeId nodeId,String url) {
    	OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url);
    	if(opcUaClient!=null) {
    		try {
                List<? extends org.eclipse.milo.opcua.sdk.client.nodes.UaNode> nodes = opcUaClient.getAddressSpace().browseNodes(nodeId);
                for (org.eclipse.milo.opcua.sdk.client.nodes.UaNode node : nodes) {
                	String name = node.getBrowseName().getName();
                	List<Object[]> newList = OpcUaClentUtils.browseNode("", opcUaClient, node.getNodeId(), new ArrayList<Object[]>(),0);
                	Object identifier = node.getNodeId().getIdentifier();
                	if(newList==null || newList.size()==0) {
                		System.out.println("boot==========="+identifier+"");
                		NodeId typeId = node.getNodeId();
                		Object valueObject = OpcUaClentUtils.readValue(opcUaClient, new NodeId(2, (identifier+"").toString()));
                		Variant variant = new Variant(valueObject);
                		addNode(folderNode,(identifier+""),name,typeId,variant,url);
                	}else {
                		System.out.println("Folder==========="+identifier+"");
                		addDataBlocksGlobalNodes(addUaFolderNode(folderNode,(identifier+""),name),node.getNodeId(),url);
                	}
                }
            } catch (UaException e) {
                logger.error("Browsing nodeId={} failed: {}", nodeId, e.getMessage(), e);
            }
    	}
    }
    
    private UaFolderNode addUaFolderNode(UaFolderNode rootNode,Object identifier,String name) {
        UaFolderNode scalarTypesFolder = new UaFolderNode(
            getNodeContext(),
            newNodeId(identifier.toString()),
            newQualifiedName(name),
            LocalizedText.english(name)
        );
        getNodeManager().addNode(scalarTypesFolder);
        rootNode.addOrganizes(scalarTypesFolder);
        return scalarTypesFolder;
    }
    
    private void addNode(UaFolderNode rootNode,Object identifier,String name,NodeId typeId,Variant variant,String url) {
        UaVariableNode node = new UaVariableNode.UaVariableNodeBuilder(getNodeContext())
            .setNodeId(newNodeId((String) identifier))
            .setAccessLevel(AccessLevel.READ_WRITE)
            .setUserAccessLevel(AccessLevel.READ_WRITE)
            .setBrowseName(newQualifiedName(name))
            .setDisplayName(LocalizedText.english(name))
            .setDataType(typeId)
            .setTypeDefinition(Identifiers.BaseDataVariableType)
            .build();

        node.setValue(new DataValue(variant));
        node.getFilterChain().addLast(
        		new AttributeLoggingFilter(),
        		AttributeFilters.getValue(
                        ctx ->{
                        	OpcUaClient opcUaClient = OpcUaClentUtils.getOpcUaClent(url);
                            Object valueObject = OpcUaClentUtils.readValue(opcUaClient, new NodeId(2, (identifier+"").toString()));
                        	return new DataValue(new Variant(valueObject));
                        }   
                    )
        		);

        getNodeManager().addNode(node);
        rootNode.addOrganizes(node);
    }

    private void startBogusEventNotifier() {
        // Set the EventNotifier bit on Server Node for Events.
        UaNode serverNode = getServer()
            .getAddressSpaceManager()
            .getManagedNode(Identifiers.Server)
            .orElse(null);

        if (serverNode instanceof ServerTypeNode) {
            ((ServerTypeNode) serverNode).setEventNotifier(ubyte(1));

            // Post a bogus Event every couple seconds
            eventThread1 = new Thread(() -> {
                while (keepPostingEvents) {
                    try {
                        BaseEventTypeNode eventNode = getServer().getEventFactory().createEvent(
                            newNodeId(UUID.randomUUID()),
                            Identifiers.BaseEventType
                        );

                        eventNode.setBrowseName(new QualifiedName(1, "foo"));
                        eventNode.setDisplayName(LocalizedText.english("foo"));
                        eventNode.setEventId(ByteString.of(new byte[]{0, 1, 2, 3}));
                        eventNode.setEventType(Identifiers.BaseEventType);
                        eventNode.setSourceNode(serverNode.getNodeId());
                        eventNode.setSourceName(serverNode.getDisplayName().getText());
                        eventNode.setTime(DateTime.now());
                        eventNode.setReceiveTime(DateTime.NULL_VALUE);
                        eventNode.setMessage(LocalizedText.english("event message!"));
                        eventNode.setSeverity(ushort(2));

                        //noinspection UnstableApiUsage
                        getServer().getEventBus().post(eventNode);

                        eventNode.delete();
                    } catch (Throwable e) {
                        logger.error("Error creating EventNode: {}", e.getMessage(), e);
                    }

                    try {
                        //noinspection BusyWait
                        Thread.sleep(2_000);
                    } catch (InterruptedException ignored) {
                        // ignored
                    }
                }
            }, "bogus-event-poster");

            eventThread1.start();
        }
    }

    @Override
    public void onDataItemsCreated(List<DataItem> dataItems) {
        subscriptionModel.onDataItemsCreated(dataItems);
    }

    @Override
    public void onDataItemsModified(List<DataItem> dataItems) {
        subscriptionModel.onDataItemsModified(dataItems);
    }

    @Override
    public void onDataItemsDeleted(List<DataItem> dataItems) {
        subscriptionModel.onDataItemsDeleted(dataItems);
    }

    @Override
    public void onMonitoringModeChanged(List<MonitoredItem> monitoredItems) {
        subscriptionModel.onMonitoringModeChanged(monitoredItems);
    }

}
